/* global App, alertify */

Date.prototype.yyyymmdd = function() {
    var yyyy = this.getFullYear().toString();
    var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
    var dd  = this.getDate().toString();
    return yyyy + (mm[1]?mm:"0"+mm[0]) + (dd[1]?dd:"0"+dd[0]); // padding
};

App.register('Contributions', Contributions = {

    entry_type:'single_entry',

    init: function() {
        this.setup();
    },
    
    setup: function() {
        var self = this;

        $("#single_entry,#bulk_entry").change(function(){
            var me = $(this);
            self.entry_type = me.val();
            $("#bulk_receipt_no_container").hide();
            if(self.entry_type == 'bulk_entry'){
                $("#bulk_receipt_no").val('');
                $("#bulk_receipt_no_container").show('fast').focus();
            }
            var parent = me.parent();
            var top_parent = parent.parent();
            top_parent.find('label').removeClass('btn-success').addClass('btn-default');
            parent.removeClass('btn-default').addClass('btn-success');
        });

        $("#filter_contribution_types").change(function(){
            var selected = $(this).val();
            window.location = $("#collections_url").val()+'/default/'+selected
        });

        $("#btn_new_collection").click(function(e) {
            e.preventDefault();
            App.notify("collections.add");
        });

        $("#btn_save_collection").click(function(e) {
            e.preventDefault();
            App.notify("collections.save");
        });

        App.listen('collections.refresh', function() {
            window.history.go(0);
        });

    }
});


App.register("ContributionsEditor", ContributionsEditor = {

    editable_rows:0,

    init: function() {
        var self = this;

        App.listen('collections.add', function() {
            self.configure_add();
        });

        App.listen('collections.save', function() {
            self.configure_save();
        });

        $('#collections_tbl_list tbody').delegate('tr.editing td button.split_payment_btn','click',function(){
            var tr = $(this).parents().parents();
            self.split_payment(tr);
        });

        $('#collections_tbl_list tbody').delegate('tr.editing td button.save_row_btn','click',function(){
            var tr = $(this).parents().parents();
            self.process_row(tr);
        });

        $('#collections_tbl_list tbody').delegate('tr.editing td button.delete_row_btn','click',function(){
            var parent_data_id = $(this).attr('parent-data-id');
            $("tr[data-id='" + parent_data_id + "']").hide('slow').remove();
        });
    },

    configure_add: function() {
        var self = this;
        var entry_type = Contributions.entry_type;

        if(entry_type == 'bulk_entry'){
            var bulk_receipt_no = $("#bulk_receipt_no").val();
            var bulk_receipt_no = bulk_receipt_no.trim();
            if(bulk_receipt_no.length == 0){
                alertify.error("You must enter a bulk receipt number.");
                return;
            }
            else{
                self.add(entry_type,bulk_receipt_no);
            }
        }
        else{
            self.add(entry_type);
        }
    },


    split_payment: function(tr) {
        var self = this;

        var tr_id = tr.attr('data-id');

        var ram = tr.find('td input#row_amount_'+tr_id);
        var amount  = ram.val();
        amount = amount.trim();
        if(amount.length <= 0){
            var txt = 'Amount is required for split payment';
            alertify.error(txt);
            ram.addClass('field_error');
        }
        else{
            if(!jQuery.isNumeric(amount)){
                var txt = 'Amount must be numeric for split payment';
                alertify.error(txt);
                ram.addClass('field_error');
            }
            else{//Split Payment

                /*$("#split_payment_modal").modal({
                    backdrop:'static'
                });*/
            }
        }
    },


    validate_row:function(tr){
        var self = this;

        var error_obj = [];
        var tr_id = tr.attr('data-id');

        var rrdt = tr.find('td input#row_receipt_dt_'+tr_id);
        var receipt_dt = rrdt.val();
        receipt_dt = receipt_dt.trim();
        if(receipt_dt.length <= 0){
            error_obj.push({obj:rrdt,msg:'Receipt Date is required.'});
        }

        var rrn = tr.find('td input#row_receipt_no_'+tr_id);
        var receipt_no = rrn.val();
        receipt_no = receipt_no.trim();
        if(receipt_no.length <= 0){
            error_obj.push({obj:rrn,msg:'Receipt No is required.'});
        }

        var romi = tr.find('td input#row_organisation_member_id_'+tr_id);
        var rmn = tr.find('td input#row_member_name_'+tr_id);
        var organisation_member_id  = romi.val();
        organisation_member_id = organisation_member_id.trim();
        if(organisation_member_id.length <= 0){
            error_obj.push({obj:rmn,msg:'Member No is required.'});
        }

        var ram = tr.find('td input#row_amount_'+tr_id);
        var amount  = ram.val();
        amount = amount.trim();
        if(amount.length <= 0){
            error_obj.push({obj:ram,msg:'Amount is required.'});
        }
        else{
            if(!jQuery.isNumeric(amount)){
                error_obj.push({obj:ram,msg:'Amount must be numeric.'});
            }
        }

        var pty = tr.find('td select#row_payment_type_'+tr_id);
        if(pty.val() == 2){//if Cheque, validate Cheque Number
            var cqn = tr.find('td input#row_cheque_no_'+tr_id);
            var cheque_no  = cqn.val();
            cheque_no = cheque_no.trim();
            if(cheque_no.length <= 0){
                error_obj.push({obj:cqn,msg:'Cheque Number is required.'});
            }
        }

        if(error_obj.length > 0){
            var txt = '';
            for(var x in error_obj){
                var t = error_obj[x];
                txt = txt + t.msg +' <br />';
                t.obj.addClass('field_error');
            }
            alertify.error(txt);
            return false;
        }
        else{
            return true;
        }
    },

    process_row:function(tr){
        var self = this;
        //We are saving
        tr.removeClass('active').removeClass('row_error').addClass('saving');
        var res = self.validate_row(tr);
        if(res){
            self.single_save(tr);
        }
        else{ //Validation error, so back to editing
            tr.removeClass('saving').addClass('editing');
        }
    },

    select_active_row:function(select_me){
        var self = this;

        $('#collections_tbl_list tbody tr.editing').each(function(){
            var me = $(this);
            if(me.hasClass('active') && (select_me.attr('data-id') != me.attr('data-id'))){//I was the last active row, validate and save me.
                self.process_row(me);
            }
            me.removeClass('active');
        });
        select_me.addClass('active');
    },

    add:function(entry_type,bulk_receipt_no){
        var self = this;

        var d = new Date();
        var today = d.yyyymmdd();

        var tr_id = new Date().getTime();

        var tr = $('<tr />').attr('data-id','0').attr('class','editing').attr('data-id',tr_id);

        //Receipt Date
        var td = $('<td />').attr('data-value','');
        var text = $('<input />').attr('type','text').attr('class','input-sm  input-s-m form-control col-md-1').attr('placeholder','').addClass('row_receipt_dt').attr('id','row_receipt_dt_'+tr_id);
        text.focus(function(){
            var parent_tr = text.parents().parents();
            self.select_active_row(parent_tr);
        });
        text.val(today).mask("9999-99-99");
        td.append(text);
        tr.append(td);

        //Receipt No
        var td = $('<td />');
        if(entry_type == 'bulk_entry'){
            td.attr('data-value',bulk_receipt_no);
            var hidden = $('<input />').attr('type','hidden').attr('value',bulk_receipt_no).addClass('row_receipt_no').attr('id','row_receipt_no_'+tr_id);
            td.append(bulk_receipt_no).append(hidden);
        }
        else{
            //check if we are doing manual receipt ot auto receipt
            if(receipt_settings['receipt_mode'] == 'auto'){
                var new_auto_receipt = ContributionsReceiptEngine.getReceiptNumber();
                td.attr('data-value',new_auto_receipt);
                var hidden = $('<input />').attr('type','hidden').attr('value',new_auto_receipt).addClass('row_receipt_no').attr('id','row_receipt_no_'+tr_id);
                td.append("<div class='td-incell'>"+new_auto_receipt+"</div>").append(hidden);
            }
            else{//Manual receipt
                td.attr('data-value','');
                var text = $('<input />').attr('type','text').attr('class','input-sm input-s-m form-control').attr('placeholder','Receipt No.').addClass('row_receipt_no').attr('id','row_receipt_no_'+tr_id);
                text.focus(function(){
                    var parent_tr = text.parents().parents();
                    self.select_active_row(parent_tr);
                });
                td.append(text);
            }
        }
        tr.append(td);

        //Contribution Type
        var td = $('<td />').attr('data-value','');
        var select = $('<select />').attr('class','input-sm form-control input-s-sm inline').addClass('row_contributions_type').attr('id','row_contributions_type_'+tr_id);
        for(var x in contribution_types){
            var opt_data = contribution_types[x];
            var option = $('<option />').attr('value',opt_data.id).html(opt_data.name);
            select.append(option);
        }
        select.focus(function(){
            var parent_tr = text.parents().parents();
            self.select_active_row(parent_tr);
        });
        td.append(select);
        tr.append(td);

        //Member
        var td = $('<td />').attr('data-value','');
        var text = $('<input />').attr('type','text').attr('class','input-sm  input-s-sm  form-control').attr('placeholder','Type Member No.').addClass('row_member_name').attr('id','row_member_name_'+tr_id);
        text.focus(function(){
            var parent_tr = text.parents().parents();
            self.select_active_row(parent_tr);
        });
        self.bind_auto_complete(text);
        var hidden = $('<input />').attr('type','hidden').attr('value','').addClass('row_organisation_member_id').attr('id','row_organisation_member_id_'+tr_id);
        td.append(text);
        td.append(hidden);
        tr.append(td);

        //Week Paying For
        var td = $('<td />').attr('data-value','');
        var select = $('<select />').attr('class','input-sm form-control input-s-xs inline').addClass('row_week_paying').attr('id','row_week_paying_'+tr_id);
        for(var value in weeks){
            var opt_data = weeks[value];
            var option = $('<option />').attr('value',value).html(opt_data);
            select.append(option);
        }
        select.focus(function(){
            var parent_tr = text.parents().parents();
            self.select_active_row(parent_tr);
        });
        select.val(cur_week);
        td.append(select);
        tr.append(td);

        //Month Paying For
        var td = $('<td />').attr('data-value','');
        var select = $('<select />').attr('class','input-sm form-control input-s-xs inline').addClass('row_month_paying').attr('id','row_month_paying_'+tr_id);
        for(var value in months){
            var opt_data = months[value].substring(0,3);
            var option = $('<option />').attr('value',value).html(opt_data);
            select.append(option);
        }
        select.focus(function(){
            var parent_tr = text.parents().parents();
            self.select_active_row(parent_tr);
        });
        select.val(cur_month);
        td.append(select);
        tr.append(td);

        //Year Paying For
        var td = $('<td />').attr('data-value','');
        var select = $('<select />').attr('class','input-sm form-control input-s-xs inline').addClass('row_year_paying').attr('id','row_year_paying_'+tr_id);
        for(var value in years){
            var opt_data = years[value];
            var option = $('<option />').attr('value',value).html(opt_data);
            select.append(option);
        }
        select.focus(function(){
            var parent_tr = text.parents().parents();
            self.select_active_row(parent_tr);
        });
        select.val(cur_year);
        td.append(select);
        tr.append(td);


        //Payment Type
        var td = $('<td />').attr('data-value','').attr('nowrap','');

        var select = $('<select />').attr('class','input-sm form-control input-s-m pull-left inline').addClass('row_payment_type').attr('id','row_payment_type_'+tr_id);
        for(var value in payment_types){
            var value_id = payment_types[value]['id'];
            var opt_data = payment_types[value]['name'];
            var option = $('<option />').attr('value',value_id).html(opt_data);
            select.append(option);
        }
        select.focus(function(){
            var parent_tr = text.parents().parents();
            self.select_active_row(parent_tr);
        });
        select.change(function(){
            var val = $(this).val();
            if(val == 2){//Cheque then show cheque number text
                $('#row_cheque_no_'+tr_id).show('fast');
            }
            else{
                $('#row_cheque_no_'+tr_id).val('').hide('fast');
            }
        });

        var text = $('<input />').attr('type','text').attr('class','input-sm input-s-m pull-left form-control m-r-xs row_cheque_no').attr('placeholder','Cheque No.').attr('id','row_cheque_no_'+tr_id);
        text.focus(function(){
            var parent_tr = text.parents().parents();
            self.select_active_row(parent_tr);
        });
        text.hide();
        td.prepend(text);
        td.prepend(select);
        tr.append(td);


        //Amount
        var td = $('<td />').attr('data-value','').attr('nowrap','');

        var select = $('<select />').attr('class','input-sm form-control input-s-xs pull-left inline').addClass('row_currency').attr('id','row_currency_'+tr_id);
        for(var value in currencies_list){
            var opt_data = currencies_list[value];
            var option = $('<option />').attr('value',value).html(opt_data);
            select.append(option);
        }
        select.focus(function(){
            var parent_tr = text.parents().parents();
            self.select_active_row(parent_tr);
        });
        select.val(default_currency);

        var text = $('<input />').attr('type','text').attr('class','input-sm input-s-xs form-control m-r-xs row_amount').attr('placeholder','0.00').attr('id','row_amount_'+tr_id);
        text.focus(function(){
            var parent_tr = text.parents().parents();
            self.select_active_row(parent_tr);
            //Add New row automatically
            if(self.editable_rows < 2){
                App.notify("collections.add");
            }
        });
        td.append(text);
        td.prepend(select);
        /*var button = $('<button />').attr('class','btn btn-info btn-sm split_payment_btn').css('margin-top','3px').attr('id','split_payment_btn_'+tr_id).html('Split');
        td.append(button);*/

        tr.append(td);


        //Save,Delete Button or Loader
        var td = $('<td />');
        var button = $('<button />').attr('class','btn btn-info save_row_btn').attr('id','save_row_btn_'+tr_id);
        var icon = $('<i />').attr('class','fa fa-save text');
        button.append(icon);
        button.focus(function(){
            var parent_tr = button.parents().parents();
            self.select_active_row(parent_tr);
        });
        td.append(button);
        var button = $('<button />').attr('class','btn btn-danger delete_row_btn').attr('id','delete_row_btn_'+tr_id).attr('parent-data-id',tr_id);
        var icon = $('<i />').attr('class','fa fa-trash-o text');
        button.append(icon);
        td.append(button);

        var icon = $('<i />').attr('class','fa fa-spinner fa fa-spin fa-2x save_row_loader').attr('id','save_row_loader_'+tr_id).hide();
        td.append(icon);
        tr.append(td);

        var icon = $('<i />').attr('class','fa fa-check text-success fa-1x saved_row_icon').attr('id','saved_row_icon_'+tr_id).hide();
        td.append(icon);
        tr.append(td);

        //$('#collections_tbl_list tbody').prepend(tr);
        $('#collections_tbl_list tbody').append(tr);

        //Increase Count.
        self.editable_rows = self.editable_rows + 1;
    },


    bind_auto_complete:function(jquery_obj){

        jquery_obj.autocomplete({
            source: $("#contacts-autocomplete-url").val(),
            minLength: 2,
            select: function( event, ui ) {
                if ( ui.item ) {
                    var hidden = $(this).siblings('input[type=hidden]');
                    hidden.val(ui.item.organization_member_id);
                }
            },
            create: function() {
                $(this).data('ui-autocomplete')._renderItem = function( ul, item ) {
                    return $("<li class='bg-white b-b text-sm'>").append("<span class='p-xs block'>" + item.label + "</span>").appendTo(ul);
                };

                $(this).data('ui-autocomplete')._resizeMenu = function() {
                    this.menu.element.outerWidth(275);
                };
            }
        });

    },


    configure_save: function() {
        var self = this;

        if( $("#category_view #category_id").val() == "" ) {
            $("#category_view #category_name").friendurl({id: 'category_slug'});
        }

        $("#category_view #edit_btn").css({visibility: 'hidden'});

        $("#category_view #cancel-btn").click(function(e) {
            e.preventDefault();
            $("#categories-table tbody tr.selected td.info").click();
        });

        $("#category_view form").submit(function(e) {
            e.preventDefault();

            self.save();
        });
    },

    animate_row_save:function(tr,animate){
        var self = this;
        if(typeof animate == 'undefined'){
            animate = true;
        }

        var tr_id = tr.attr('data-id');
        var receipt_dt_obj = tr.find('td input#row_receipt_dt_'+tr_id);
        var receipt_no_obj = tr.find('td input#row_receipt_no_'+tr_id);
        var row_member_name_obj  = tr.find('td input#row_member_name_'+tr_id);
        var amount_obj  = tr.find('td input#row_amount_'+tr_id);
        var currency_obj  = tr.find('td select#row_currency_'+tr_id);
        var payment_type_obj  = tr.find('td select#row_payment_type_'+tr_id);
        var cheque_no_obj  = tr.find('td input#row_cheque_no_'+tr_id);
        var contributions_type_obj  = tr.find('td select#row_contributions_type_'+tr_id);
        var week_paying_obj  = tr.find('td select#row_week_paying_'+tr_id);
        var month_paying_obj  = tr.find('td select#row_month_paying_'+tr_id);
        var year_paying_obj  = tr.find('td select#row_year_paying_'+tr_id);
        var button_obj = tr.find('td button#save_row_btn_'+tr_id);
        var delete_btn_obj = tr.find('td button#delete_row_btn_'+tr_id);
        var loader_obj = tr.find('td i#save_row_loader_'+tr_id);
        var split_payment_obj  = tr.find('td button#split_payment_btn_'+tr_id);

        if(animate){
            receipt_dt_obj.attr('disabled','disabled').removeClass('field_error');
            receipt_no_obj.attr('disabled','disabled').removeClass('field_error');
            row_member_name_obj.attr('disabled','disabled').removeClass('field_error');
            amount_obj.attr('disabled','disabled').removeClass('field_error');
            currency_obj.attr('disabled','disabled').removeClass('field_error');
            payment_type_obj.attr('disabled','disabled').removeClass('field_error');
            cheque_no_obj.attr('disabled','disabled').removeClass('field_error');
            contributions_type_obj.attr('disabled','disabled').removeClass('field_error');
            week_paying_obj.attr('disabled','disabled').removeClass('field_error');
            month_paying_obj.attr('disabled','disabled').removeClass('field_error');
            year_paying_obj.attr('disabled','disabled').removeClass('field_error');
            split_payment_obj.hide();
            button_obj.hide();
            delete_btn_obj.hide();
            loader_obj.show();
        }
        else{
            receipt_dt_obj.removeAttr('disabled').removeClass('field_error');
            receipt_no_obj.removeAttr('disabled').removeClass('field_error');
            row_member_name_obj.removeAttr('disabled').removeClass('field_error');
            amount_obj.removeAttr('disabled').removeClass('field_error');
            currency_obj.removeAttr('disabled').removeClass('field_error');
            payment_type_obj.removeAttr('disabled').removeClass('field_error');
            cheque_no_obj.removeAttr('disabled').removeClass('field_error');
            contributions_type_obj.removeAttr('disabled').removeClass('field_error');
            week_paying_obj.removeAttr('disabled').removeClass('field_error');
            month_paying_obj.removeAttr('disabled').removeClass('field_error');
            year_paying_obj.removeAttr('disabled').removeClass('field_error');
            split_payment_obj.show();
            button_obj.show();
            delete_btn_obj.show();
            loader_obj.hide();
        }

    },

    single_save:function(tr){
        var self = this;

        var tr_id = tr.attr('data-id');
        var receipt_dt = tr.find('td input#row_receipt_dt_'+tr_id).val();
        var receipt_no = tr.find('td input#row_receipt_no_'+tr_id).val();
        var organisation_member_id  = tr.find('td input#row_organisation_member_id_'+tr_id).val();
        var amount  = tr.find('td input#row_amount_'+tr_id).val();
        var currency  = tr.find('td select#row_currency_'+tr_id).val();
        var payment_type  = tr.find('td select#row_payment_type_'+tr_id).val();
        var cheque_no  = tr.find('td input#row_cheque_no_'+tr_id).val();
        var contributions_type  = tr.find('td select#row_contributions_type_'+tr_id).val();
        var week_paying  = tr.find('td select#row_week_paying_'+tr_id).val();
        var month_paying  = tr.find('td select#row_month_paying_'+tr_id).val();
        var year_paying  = tr.find('td select#row_year_paying_'+tr_id).val();

        //Animate Saving
        self.animate_row_save(tr,true);

        var query = [];
        var data = {
            'tr_data_id':tr.attr('data-id'),
            'receipt_dt':receipt_dt,
            'receipt_no':receipt_no,
            'organisation_member_id':organisation_member_id,
            'amount':amount,
            'currency':currency,
            'payment_type':payment_type,
            'cheque_no':cheque_no,
            'contributions_type':contributions_type,
            'week_paying':week_paying,
            'month_paying':month_paying,
            'year_paying':year_paying
        };
        query.push(data);
        self.save(query,tr,receipt_no);
    },

    save: function(data,tr,receipt_no) {
        var self = this;

        var url = $("#collections_url").val()+'/save';
        var params = 'data='+encodeURIComponent(JSON.stringify(data));

        $.ajax({
            url: url,
            data: params,
            type: 'post',
            dataType: 'json',
            success: function(res) {
                self.animate_row_save(tr,false);
                if( typeof res['status'] != "undefined" ) {
                    if( res['status'] == 'success' ) {
                        //alertify.success(res['message']);
                        if(receipt_settings['receipt_mode'] == 'auto'){
                            ContributionsReceiptEngine.resetReceiptCounter(receipt_no);
                            //App.notify("module_receipt_engine.update",receipt_no);
                        }
                        self.post_save(res.data);
                    }
                    else {
                        alertify.error(res['message']);
                    }
                }
                else {
                    alertify.error(JSON.stringify(res));
                }
            },
            error: function() {
                self.animate_row_save(tr,false);
                alertify.error("Failed to save member contribution.");
            }
        });
    },


    post_save:function(data){
        var self = this;

        for(var x in data){
            var tr_id = data[x]['ModuleContributionReceipt']['tr_data_id'];
            var tr = $("tr[data-id='" + tr_id + "']").removeClass();
            var err = data[x]['Error'];
            if(typeof err == 'undefined'){

                var receipt_dt_obj = tr.find('td input#row_receipt_dt_'+tr_id);
                var parent_td = receipt_dt_obj.parent('td');
                parent_td.html(receipt_dt_obj.val());
                receipt_dt_obj.remove();

                var receipt_no_obj = tr.find('td input#row_receipt_no_'+tr_id);
                var parent_td = receipt_no_obj.parent('td');
                parent_td.html(receipt_no_obj.val());
                receipt_no_obj.remove();

                var row_member_name_obj  = tr.find('td input#row_member_name_'+tr_id);
                var parent_td = row_member_name_obj.parent('td');
                parent_td.html(row_member_name_obj.val());
                row_member_name_obj.remove();

                var payment_type_obj  = tr.find('td select#row_payment_type_'+tr_id);
                var cheque_no_obj  = tr.find('td input#row_cheque_no_'+tr_id);
                var text  = payment_type_obj.find("option:selected").text();
                var parent_td = cheque_no_obj.parent('td');
                var html = text+'  &nbsp; ';
                var cheq_no = cheque_no_obj.val();
                cheq_no = cheq_no.trim();
                if(cheq_no.length > 0 ){
                    html += '( '+cheq_no+' ) Not Cleared';
                }
                parent_td.html(html);
                payment_type_obj.remove();
                cheque_no_obj.remove();

                var amount_obj  = tr.find('td input#row_amount_'+tr_id);
                var currency_obj  = tr.find('td select#row_currency_'+tr_id);
                var text  = currency_obj.find("option:selected").text();
                var parent_td = amount_obj.parent('td');
                var html = text+' '+amount_obj.val();
                parent_td.html(html);
                amount_obj.remove();
                currency_obj.remove();

                var contributions_type_obj  = tr.find('td select#row_contributions_type_'+tr_id);
                var text  = contributions_type_obj.find("option:selected").text();
                var parent_td = contributions_type_obj.parent('td');
                parent_td.html(text);
                contributions_type_obj.remove();

                var week_paying_obj  = tr.find('td select#row_week_paying_'+tr_id);
                var parent_td = week_paying_obj.parent('td');
                var text  = week_paying_obj.find("option:selected").text();
                parent_td.html(text);
                week_paying_obj.remove();

                var month_paying_obj  = tr.find('td select#row_month_paying_'+tr_id);
                var parent_td = month_paying_obj.parent('td');
                var text  = month_paying_obj.find("option:selected").text();
                parent_td.html(text);
                month_paying_obj.remove();

                var year_paying_obj  = tr.find('td select#row_year_paying_'+tr_id);
                var parent_td = year_paying_obj.parent('td');
                var text  = year_paying_obj.find("option:selected").text();
                parent_td.html(text);
                year_paying_obj.remove();

                var saved_row_icon_obj  = tr.find('td i#saved_row_icon_'+tr_id).show();
                var button_obj = tr.find('td button#save_row_btn_'+tr_id).remove();
                var delete_btn_obj = tr.find('td button#delete_row_btn_'+tr_id).remove();
                var loader_obj = tr.find('td i#save_row_loader_'+tr_id).remove();
                var split_payment_obj  = tr.find('td button#split_payment_btn_'+tr_id).remove();

                //Increase Count.
                self.editable_rows = self.editable_rows - 1;
            }
            else{
                tr.removeClass('saving').addClass('editing').addClass('row_error');
                alertify.error(err);
            }

        }
    }
});



App.register('ContributionsReceiptEngine', ContributionsReceiptEngine = {

    receipt_counter:'',
    receipt_generated:[],
    receipt_settings:{},

    init: function() {
        this.setup();
    },

    setup: function() {
        var self = this;

        self.receipt_settings = receipt_settings;

        App.listen('module_receipt_engine.update', function(receipt_value) {
            self.resetReceiptCounter(receipt_value);
        });
    },

    getReceiptNumber: function() {
        var self = this;
        var max = parseInt(self.getHighestValue());
        if(max == 0){
            max =  parseInt(self.receipt_settings['receipt_counter']);
            if(max != 1){
                max = max + 1;
            }
        }
        else{
            max = max + 1;
        }
        var prefix =  receipt_settings['receipt_prefix'];
        var postfix =  receipt_settings['receipt_postfix'];
        var receipt_value = prefix+''+max+''+postfix;
        self.receipt_generated.push({
            id:max,
            value:receipt_value,
            status:'new'
        });

        return receipt_value;
    },

    getHighestValue:function(){
        var self = this;

        var arr = self.receipt_generated;
        if(arr.length > 0){
            var max = arr[0]['id'];
        }
        else{
            var max = 0;
        }

        var maxIndex = 0;
        for (var i = 1; i < arr.length; i++) {
            if (arr[i]['id'] > max) {
                maxIndex = i;
                max = arr[i]['id'];
            }
        }

        return max;
    },

    resetReceiptCounter: function(receipt_value) {
        var self = this;

        var arr = self.receipt_generated;
        for (var i = 1; i < arr.length; i++) {
            if (arr[i]['value'] == receipt_value) {
                self.receipt_counter = arr[i]['id'];
            }
        }
        self.updateReceiptCounter();
    },

    updateReceiptCounter: function() {
        var self = this;

        var url = $("#set_new_receipt_counter_url").val();
        var params = "receipt_counter="+self.receipt_counter;

        $.ajax({
            url: url,
            data: params,
            type: 'post',
            dataType: 'json',
            success: function(res) {
                if( typeof res['status'] != "undefined" ) {
                    if( res['status'] == 'success' ) {
                        self.markAsSaved();
                    }
                    else {
                        //alertify.error(res['message']);
                    }
                }
                else {
                    alert(JSON.stringify(res));
                }
            },
            error: function() {
                alert("Failed to save changes to membership category.");
            }
        });
    },

    markAsSaved:function(){
        var self = this;

        var arr = self.receipt_generated;
        for (var i = 1; i < arr.length; i++) {
            if (arr[i]['id'] == self.receipt_counter) {
                self.receipt_generated[i]['status'] = 'saved';
            }
        }
    }
});
